package org.aeon.colorfulplanebattle.view.logic;

import org.aeon.colorfulplanebattle.constant.GameStateE;
import org.aeon.colorfulplanebattle.flying.entity.Bullet;
import org.aeon.colorfulplanebattle.flying.entity.CollisionPairs;
import org.aeon.colorfulplanebattle.flying.entity.Plane;
import org.aeon.colorfulplanebattle.flying.entity.Ship;
import org.aeon.colorfulplanebattle.view.GameState;
import org.aeon.colorfulplanebattle.view.components.PopUp;
import org.aeon.colorfulplanebattle.view.panel.SettlementPage;

import java.util.Deque;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * @author: MissingAeon
 * @date: 2024/1/12 13:27
 * @description:
 */
public class TaskManage {
    private static ScheduledExecutorService timer;// 计算线程
    private static GameState gameState;
    private static TimerTask flyDrawTask;
    private static TimerTask taskManage;

    public static void startUp() {
        timer.scheduleAtFixedRate(flyDrawTask, 1, 1, TimeUnit.MILLISECONDS);
        timer.scheduleAtFixedRate(taskManage, 1, 10, TimeUnit.MILLISECONDS);
    }

    public static void prepare(GameState gameState) {
        TaskManage.gameState = gameState;
        timer = Executors.newScheduledThreadPool(2);
        // 创建己方飞机对象
        Plane myPlane = new Plane();
        gameState.put("myPlane", myPlane);
        List<Ship> ships = new CopyOnWriteArrayList<>();
        List<Bullet> bullets = new CopyOnWriteArrayList<>();
        Deque<CollisionPairs> hit = new ConcurrentLinkedDeque<>();
        flyDrawTask = new FlyDrawTask(gameState, myPlane, ships, bullets, hit);
        gameState.put("flyCtrl", flyDrawTask);
        taskManage = new GameJudgeTask(gameState, myPlane, ships, hit, bullets);
    }

    public static void finish() {
        // 结束任务
        flyDrawTask.cancel();
        taskManage.cancel();
        // 结束线程
        timer.shutdown();
        // 结算
        PopUp popUp = new PopUp(gameState, new SettlementPage(gameState));
        gameState.put("settlement", popUp);
        gameState.setState(GameStateE.SCORING);
    }
}
